package model

import (
	"fmt"
	"go_web/test_demo/demo6_db/utils"
)

type User struct {
	ID       int
	Username string
	Password string
	Email    string
}

// add 添加数据方法一:
func (user *User) AddUser1() error {
	// 1、 sql
	sqlStr := "insert into user(username,password,email) values(?,?,?)"
	// 2、 预编译
	inStmt, err := utils.Db.Prepare(sqlStr)
	if err != nil {
		fmt.Println("预编译出现异常: ", err)
		return err
	}
	// 3、 执行
	_, err2 := inStmt.Exec("admin1", "123", "123@qq.com")
	if err2 != nil {
		fmt.Println("sql执行异常: ", err2)
		return err2
	}
	return nil
}

// add 添加数据方法二:
func (user *User) AddUser2() error {
	// 1、 sql
	sqlStr := "insert into user(username,password,email) values(?,?,?)"
	// 2、 执行
	_, err := utils.Db.Exec(sqlStr, "admin2", "456", "456@qq.com")
	if err != nil {
		fmt.Println("sql执行异常: ", err)
		return err
	}
	return nil
}

// 根据用户id从数据库查一条数据
func (user *User) GetUserByID() (*User, error) {
	sqlStr := "select * from user where id = ?"
	row := utils.Db.QueryRow(sqlStr, user.ID)
	// 声明变量
	var (
		id                        int
		username, password, email string
	)
	err := row.Scan(&id, &username, &password, &email)
	if err != nil {
		return nil, err
	}
	u := &User{
		ID:       id,
		Username: username,
		Password: password,
		Email:    email,
	}
	return u, nil
}

// 获取所有user记录
func (user *User) GetUsers() ([]*User, error) {
	sqlStr := "select * from user"
	rows, err := utils.Db.Query(sqlStr)
	if err != nil {
		return nil, err
	}
	// 创建user切片
	var users []*User
	for rows.Next() {
		var (
			id                        int
			username, password, email string
		)
		err := rows.Scan(&id, &username, &password, &email)
		if err != nil {
			return nil, err
		}
		u := &User{
			ID:       id,
			Username: username,
			Password: password,
			Email:    email,
		}
		users = append(users, u)
	}
	return users, nil
}
